package wang.aweb.childcar.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import wang.aweb.childcar.common.ApiRestResponse;
import wang.aweb.childcar.common.Constant;
import wang.aweb.childcar.exception.CarException;
import wang.aweb.childcar.exception.CarExceptionEnum;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

@RestController
public class UploadController {
    @PostMapping("img/upload")
    public ApiRestResponse uploadImage(HttpServletRequest httpServletRequest, @RequestParam("childcarImg") MultipartFile childcarImg) throws IOException {
        String fileName=childcarImg.getOriginalFilename();

        String suffixName=fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称uuid
        UUID uuid=UUID.randomUUID();
        String newFileName=uuid.toString()+suffixName;
        //创建文件
        File fileDirectory=new File(Constant.FILE_UPLOAD_DIR);
        File destFile=new File(Constant.FILE_UPLOAD_DIR+newFileName);
        createFile(childcarImg, fileDirectory, destFile);

        try {
            return ApiRestResponse.success(getHost(new URI(httpServletRequest.getRequestURL()+""))+"/images/"+ newFileName);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            return ApiRestResponse.error(CarExceptionEnum.UPLOAD_FAILED);
        }

    }
    private URI getHost(URI uri){
        URI effectiveURI;
        try {
            effectiveURI=new URI(Constant.IMG_DOMAIN);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            effectiveURI=null;
        }
        System.out.println(effectiveURI);
        return effectiveURI;
    }
    private void createFile(MultipartFile file, File fileDirectory, File destFile) {
        if(!fileDirectory.exists()){
            if(!fileDirectory.mkdir()){
                throw new CarException(CarExceptionEnum.MKDIR_FAILED);
            }
        }
        try{
            file.transferTo(destFile);
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
